import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import store from '../store/index.js'

import { Message } from 'element-ui';

// const originalPush = VueRouter.prototype.push
// VueRouter.prototype.push = function push (location, onResolve, onReject) {
//   if (onResolve || onReject){
//     return originalPush.call(this, location, onResolve, onReject)
//   }
//   return originalPush.call(this, location).catch(err => err)
// }

Vue.use(VueRouter)

import NProgress from "nprogress"; // 进度条；进度指示器
import "nprogress/nprogress.css"; // 进度条；进度指示器 样式
// 配置
NProgress.inc(0.2);
NProgress.configure({
	easing: "ease",
	speed: 500,
	showSpinner: false
});

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/about',
    name: 'about',
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue'),
    meta:{
      needLogin:true
    },
  }
]

const scrollBehavior = (to, from, savedPosition) => {
	if (savedPosition) {
		return savedPosition
	} else {
		return {
			x: 0,
			y: 0
		}
	}
}

const router = new VueRouter({
  routes,
  scrollBehavior
})

router.beforeEach((to, from, next) => {
	let token = window.localStorage.getItem('token')
	if(token){
		store.dispatch('vuex_get_user_info')
		store.commit('setLoginStatus',true)
	}
	
	if(to.meta.needLogin && !store.state.isLogin){
		Message({
			type:'error',
			message:'请登录后再操作',
			duration:1500
		})
		// setTimeout(()=>{
		// 	store.commit('setLoginDialog',true)
		// },1500)
		next(from.meta.needLogin ? '/' : from.fullPath);
	}else{
		NProgress.start();
		next();
	}
	
});
router.afterEach(() => {
	NProgress.done();
});

export default router
